package com.kingyun.gpsinspection.purificationservice.services.tdm.quartzjob;

import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.QueryMTAndPIService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by jiangjx on 2017/2/27.
 */

public class CreateSubTaskJob extends QuartzJobBean {
    public Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private QueryMTAndPIService queryMTAndPIService;
    @Autowired
    private PatrolInspectionMapper patrolInspectionMapper;
    @Autowired
    private TdmWorkOrderMapper tdmWorkOrderMapper;
    @Autowired
    private MaintenanceMapper maintenanceMapper;
    @Autowired
    private WorkOrderEmployeeMapper workOrderEmployeeMapper;
    @Autowired
    private TdmFileMapper tdmFileMapper;
    @Autowired
    private CustomWorkCriteriaMapper customWorkCriteriaMapper;
    //BPM管理员账号
    @Value("#{configProperties['initialLead']}")
    private Integer initialLead;

    /**
     * 定时任务主方法。入口
     *
     * @param context
     * @throws JobExecutionException
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("周期任务开始" + dateFormat.format(new Date()));
        //查询巡回检查与维护保养中符合条件的主任务
        List<QueryMTAndPIVo> mainTaskInfo = queryMTAndPIService.queryMTAndPIList();
        //遍历主任务
        for (QueryMTAndPIVo vo : mainTaskInfo) {
            //查询子任务
            List<QueryMTAndPIVo> subTaskList = queryMTAndPIService.querySubtask(vo.getTaskId());
            //查询主任务下的工单
            List<WorkOrder> workOrders = tdmWorkOrderMapper.findListByTaskId(vo.getTaskId());
            //如果不存在子任务则直接创建，如果存在子任务则通过子任务来创建
            Boolean tempFlag;
            if (null != subTaskList && subTaskList.size() > 0) {
                //根据子任务信息创建子任务
                tempFlag = decompositionTask(subTaskList, vo, workOrders);
            } else {
                //根据主任务信息创建子任务
                tempFlag = decompositionTask(vo, workOrders);
            }
            //根据是否完成状态来修改主任务
            updateMainTask(tempFlag, vo);
        }
        logger.info("周期任务结束" + dateFormat.format(new Date()));
    }

    /**
     * 根据是否完成状态来修改主任务
     *
     * @param vo       主任务信息
     * @param tempFlag 是否完成
     */
    private void updateMainTask(Boolean tempFlag, QueryMTAndPIVo vo) {
        if (tempFlag && vo.getTaskType() == 1) {
            PatrolInspection patrolInspection = new PatrolInspection();
            patrolInspection.setIsUsed(new Short("1"));
            patrolInspection.setPatrolInspectionId(vo.getTaskId());
            patrolInspectionMapper.updateByPrimaryKeySelective(patrolInspection);
        } else if (tempFlag && vo.getTaskType() == 3) {
            Maintenance maintenance = new Maintenance();
            maintenance.setIsUsed(new Short("1"));
            maintenance.setMaintenanceId(vo.getTaskId());
            maintenanceMapper.updateByPrimaryKeySelective(maintenance);
        }
    }

    /**
     * 通过主任务信息来创建子任务
     *
     * @param vo         主任务信息
     * @param workOrders
     * @return Boolean
     */
    private Boolean decompositionTask(QueryMTAndPIVo vo, List<WorkOrder> workOrders) {
        if (isFastCreate(vo)) {
            if (vo.getTaskType() == 1) {
                return createPatrolInspection(null, vo, workOrders);//创建巡回检查
            } else if (vo.getTaskType() == 3) {
                return createMaintenance(null, vo, workOrders);//创建
            }
        }
        return false;
    }

    private boolean isFastCreate(QueryMTAndPIVo vo) {
        //获取当前时间
        Date currentTime = new Date();
        //获取计划开始时间
        Date scheduledStartDate = vo.getValidityStartTime();
        //获取计划开始时间提前区间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(scheduledStartDate);
        calendar.add(Calendar.MINUTE, -initialLead);//提前量之前的时间
        Long initialLeadDate = calendar.getTimeInMillis();
        //比对是否可以创建,(满足条件1:当前时间大于计划开始时间.条件2:当前时间处于计划开始时间提前区间内)
        if (currentTime.getTime() > scheduledStartDate.getTime() || (initialLeadDate < currentTime.getTime() && currentTime.getTime() < scheduledStartDate.getTime())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 通过子任务信息来创建子任务
     *
     * @param subTaskList 子任务列表
     * @param vo
     * @param workOrders
     * @return Boolean
     */
    private Boolean decompositionTask(List<QueryMTAndPIVo> subTaskList, QueryMTAndPIVo vo, List<WorkOrder> workOrders) {
        try {
            //根据子任务的计划开始时间选择最后一个子任务的信息
            QueryMTAndPIVo subTask = getLastInfo(subTaskList);
            //判断当前是否可以创建子任务
            Boolean isCreate = isCreate(subTask, vo);
            if (isCreate) {
                if (vo.getTaskType() == 1) {
                    //创建巡回检查
                    return createPatrolInspection(subTask, vo, workOrders);
                } else if (vo.getTaskType() == 3) {
                    //创建维护保养
                    return createMaintenance(subTask, vo, workOrders);
                }
            } else {
                //如果子任务的结束日期大于主任务的周期结束日期，证明该周期任务已经执行完毕。
                if (subTask.getPlanEndTime().getTime() >= vo.getValidityEndTime().getTime()) {
                    return true;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 根据推算出来的计划开始时间来判定是否可以创建子任务，没有必要再去推算计划结束时间。
     *
     * @param subTask 子任务信息
     * @param vo      主任务信息
     */
    private Boolean isCreate(QueryMTAndPIVo subTask, QueryMTAndPIVo vo) {
        //通过主任务周期和子任务第几期来获取开始结束时间
        Date beginDate;
        //推算计划开始时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(vo.getValidityStartTime());
        if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("小时")) {
            calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + vo.getPeriodValue() * subTask.getCycle());//让小时增加周期值
        }
        if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("日")) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue() * subTask.getCycle());//让日增加周期值
        }
        if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("周")) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue() * subTask.getCycle() * 7);//让周增加周期值
        }
        if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("月")) {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + vo.getPeriodValue() * subTask.getCycle());//让月增加周期值
        }
        if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("年")) {
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + vo.getPeriodValue() * subTask.getCycle());//让年增加周期值
        }
        beginDate = calendar.getTime();

        //获取当前时间
        Date currentTime = new Date();
        //获取计划开始时间的提前量时间
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(beginDate);
        calendar2.add(Calendar.MINUTE, -initialLead);//提前量之前的时间
        //用当前时间与提前的计划时间对比
        if (currentTime.getTime() >= calendar2.getTimeInMillis()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 创建维护保养
     *
     * @param subTask    子任务信息
     * @param vo         主任务信息
     * @param workOrders 工单列表
     * @return Boolean 主任务是否执行完毕
     */
    private Boolean createMaintenance(QueryMTAndPIVo subTask, QueryMTAndPIVo vo, List<WorkOrder> workOrders) {
        Maintenance maintenance;
        if (null != subTask) {
            maintenance = formatMTaskInfo(subTask, getTime(subTask, vo, 1), getTime(subTask, vo, 2), vo.getTaskName());//根据子任务来封装数据
        } else {
            maintenance = formatMTaskInfo(vo, getTime(vo, 1), getTime(vo, 2), vo.getTaskName());//根据主任务来封装数据
        }
        return doOperate(null, maintenance, workOrders, vo);//执行维护保养后续操作
    }

    /**
     * 第一次创建生成计划开始、计划结束时间
     *
     * @param flag 标志位
     * @param vo   主任务信息
     */
    private Date getTime(QueryMTAndPIVo vo, int flag) {
        Date reTime = null;
        /**
         * 1：开始时间。2：结束时间
         * */
        if (flag == 1) {
            reTime = vo.getValidityStartTime();
        } else if (flag == 2) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(vo.getValidityStartTime());
            if (null != vo.getCommandId() && vo.getCommandId() != "") {
                calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + Integer.parseInt(vo.getCommandId()));//让小时增加用户的耗时
            } else {
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("小时")) {
                    calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + vo.getPeriodValue());//让小时增加周期值
                }
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("日")) {
                    calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue());//让日增加周期值
                }
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("周")) {
                    calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue() * 7);//让周增加周期值
                }
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("月")) {
                    calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + vo.getPeriodValue());//让月增加周期值
                }
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("年")) {
                    calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + vo.getPeriodValue());//让年增加周期值
                }
            }
            reTime = calendar.getTime();
        }
        return reTime;
    }

    /**
     * 执行后续相关操作
     *
     * @param patrolInspection 巡回检查封装类
     * @param maintenance      维护保养封装类
     * @param workOrders       工单数据
     * @param vo               主任务数据
     */
    private Boolean doOperate(PatrolInspection patrolInspection, Maintenance maintenance, List<WorkOrder> workOrders, QueryMTAndPIVo vo) {
        Date tempDate = null;
        String taskId;
        try {
            if (null == patrolInspection) {
                tempDate = maintenance.getPlanEndTime();
                //插入子任务
                maintenanceMapper.insert(maintenance);
                taskId = maintenance.getMaintenanceId();
            } else {
                tempDate = patrolInspection.getPlanEndTime();
                //插入子任务
                patrolInspectionMapper.insert(patrolInspection);
                taskId = patrolInspection.getPatrolInspectionId();
            }
            addFile(vo, maintenance, patrolInspection);//插入关联的附件信息
            addWorkOrders(workOrders, taskId, maintenance, patrolInspection);//添加工单
            if (null == patrolInspection) {
                maintenance.setAuditStatus(new Short("1"));//set子任务状态
                maintenanceMapper.updateAuditStatusById(maintenance);//修改子任务状态
            } else {
                patrolInspection.setAuditStatus(new Short("1"));//set任务状态
                patrolInspectionMapper.updateAuditStatusById(patrolInspection);//修改子任务状态
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);//打印错误日志
            return false;
        } finally {
            //如果子任务的结束日期大于主任务的周期结束日期，证明该周期任务已经执行完毕。
            if (tempDate.getTime() >= vo.getValidityEndTime().getTime()) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 添加关联的附件信息
     *
     * @param vo               主任务信息
     * @param patrolInspection 巡回检查封装类
     * @param maintenance      维护保养封装类
     */
    private void addFile(QueryMTAndPIVo vo, Maintenance maintenance, PatrolInspection patrolInspection) {
        List<File> files = tdmFileMapper.queryByBusinessId(vo.getTaskId());//查询主任务附件信息
        if (null != files && files.size() > 0) {
            for (File file : files) {
                file.setFileId(UniqueUtil.uuid());//set主键
                file.setBusinessId(null == maintenance ? patrolInspection.getPatrolInspectionId() : maintenance.getMaintenanceId());//set子任务id
            }
            tdmFileMapper.insertByList(files);//插入子任务附件信息
        }
    }


    /**
     * 封装维护保养数据
     *
     * @param subTask   子任务信息
     * @param startTime 计划开始时间
     * @param endTime   计划结束时间
     * @param taskName  主任务名称
     * @return Maintenance 维护保养封装类
     */
    private Maintenance formatMTaskInfo(QueryMTAndPIVo subTask, Date startTime, Date endTime, String taskName) {
        Maintenance task = new Maintenance();
        task.setTaskType(subTask.getTaskType());//set任务类型
        task.setTaskName(taskName);//set任务名称
        task.setTaskContent(subTask.getTaskContent());//set任务内容
        task.setIsPeriodicTask(new Short("0"));//set是否周期任务
        task.setWorkInstanceId(subTask.getWorkInstanceId());//set工作内容ID
        task.setCommandId(subTask.getCommandId());//set相关工作指令
        task.setPlanId(subTask.getPlanId());//set相关工作计划
        task.setOrgId(subTask.getOrgId());//set创建组织
        task.setCreateTime(new Date());//set创建时间
        task.setModifyTime(new Date());//set修改时间
        task.setRemark(subTask.getRemark());//set备注
        task.setParentId(null == subTask.getValidityStartTime() ? subTask.getParentId() : subTask.getTaskId());//set父任务ID
        task.setMaintenanceId(UniqueUtil.uuid());//set主键ID
        task.setCreateUserId(subTask.getCreateUserId());//set创建人
        task.setModifyUserId(subTask.getModifyUserId());//set修改人
        task.setAuditStatus(new Short("-1")); // -1 正在审核；1 审核通过；0审核不通过
        task.setIsDelete(new Short("0")); // 状态0正常；1是删除
        task.setIsEnable(new Short("1"));// 状态1是启用；0是关闭
        task.setTaskStatus(new Short("2"));// 1 审核处理中；2 执行中；3 已完成
        task.setNode(new Short("1")); // 当前节点
        task.setPlanStartTime(startTime);//计划开始时间
        task.setPlanEndTime(endTime);//计划结束时间
        //set第几次子任务
        task.setCycle(null == subTask.getCycle() ? 1 : subTask.getCycle() + 1);
        return task;
    }

    /**
     * 创建巡回检查
     *
     * @param subTask    子任务信息
     * @param vo         主任务信息
     * @param workOrders 工单列表
     * @return Boolean 主任务是否执行完毕
     */
    private Boolean createPatrolInspection(QueryMTAndPIVo subTask, QueryMTAndPIVo vo, List<WorkOrder> workOrders) {
        PatrolInspection patrolInspection;
        if (null == subTask) {
            //根据主任务来封装数据
            patrolInspection = formatPTaskInfo(vo, getTime(vo, 1), getTime(vo, 2), vo.getTaskName());
        } else {
            //根据子任务来封装数据
            patrolInspection = formatPTaskInfo(subTask, getTime(subTask, vo, 1), getTime(subTask, vo, 2), vo.getTaskName());
        }
        return doOperate(patrolInspection, null, workOrders, vo);//执行巡回检查相关操作
    }

    /**
     * 为子任务添加关联工单
     *
     * @param workOrders       主任务工单列表
     * @param taskId
     * @param maintenance      维护保养
     * @param patrolInspection 巡回检查
     */

    private void addWorkOrders(List<WorkOrder> workOrders, String taskId, Maintenance maintenance, PatrolInspection patrolInspection) {
        if (null != workOrders && workOrders.size() != 0) {
            List<WorkOrderVo> workOrderVos = formatWorkOrderList(workOrders, taskId, null == maintenance ? patrolInspection.getPlanStartTime() : maintenance.getPlanStartTime(), null == maintenance ? patrolInspection.getPlanEndTime() : maintenance.getPlanEndTime());
            tdmWorkOrderMapper.insertByList(workOrderVos);//保存工单
            List<WorkOrderEmployee> userList = formatWorkOrderEmployee(workOrderVos);//格式化人员信息
            //有人员信息才执行添加操作
            if (null != userList && userList.size() > 0) {
                workOrderEmployeeMapper.insertList(userList);//保存工单关联人员
            }

        }
    }

    /**
     * 封装工单信息
     *
     * @param workOrders 主任务工单信息
     * @param taskId     任务id
     * @param startTime  计划开始时间
     * @param endTime    计划结束时间
     */
    private List<WorkOrderVo> formatWorkOrderList(List<WorkOrder> workOrders, String taskId, Date startTime, Date endTime) {
        List<WorkOrderVo> workOrderVos = new ArrayList<>();
        for (WorkOrder workOrder : workOrders) {
            WorkOrderVo workOrderVo = new WorkOrderVo();
            BeanUtils.copyProperties(workOrder, workOrderVo);//复制属性主任务工单属性
            workOrderVo.setStatus((short) 0);
            workOrderVo.setWorkOrderId(UniqueUtil.uuid());//重设主键ID
            workOrderVo.setTaskId(taskId);//重设任务id
            List<WorkOrderEmployee> userList = workOrderEmployeeMapper.selectByWorkOrderId(workOrder.getWorkOrderId());//查询工单关联的用户信息
            for (WorkOrderEmployee workOrderEmployee : userList) {
                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());//重设人员关联主键id
                workOrderEmployee.setWorkOrderId(workOrderVo.getWorkOrderId());//重设人员关联工单id
            }
            workOrderVo.setWorkOrderEmployees(userList);
            workOrderVo.setStartTime(startTime);//重设工单计划开始时间
            workOrderVo.setFinishTime(endTime);//重设工单计划完成时间
            workOrderVo.setWorkOrderName(workOrder.getWorkOrderName());//重设工单名称
            workOrderVos.add(workOrderVo);

            //保存自定义巡检
            CustomWorkCriteria customWorkCriteria = new CustomWorkCriteria();
            customWorkCriteria.setWorkOrderId(workOrder.getWorkOrderId());
            List<CustomWorkCriteria> workCriterias = customWorkCriteriaMapper.queryListByWorkOrderId(customWorkCriteria);
            for (CustomWorkCriteria workCriteria : workCriterias) {
                workCriteria.setId(UniqueUtil.uuid());
                workCriteria.setWorkOrderId(workOrderVo.getWorkOrderId());
            }
            if (workCriterias.size() > 0) {
                customWorkCriteriaMapper.insertByList(workCriterias);
            }

        }
        return workOrderVos;
    }

    /**
     * 封装工单关联人员信息
     */
    private List<WorkOrderEmployee> formatWorkOrderEmployee(List<WorkOrderVo> workOrderVos) {
        List<WorkOrderEmployee> list = new ArrayList<>();
        for (WorkOrderVo workOrderVo : workOrderVos) {
            list.addAll(workOrderVo.getWorkOrderEmployees().stream().collect(Collectors.toList()));
        }
        return list;
    }

    /**
     * 通过子任务来获取计划开始、计划结束时间
     *
     * @param subTask 子任务数据
     * @param vo      主任务数据
     * @param flag    标识位
     * @return startTime  计划开始时间
     */
    private Date getTime(QueryMTAndPIVo subTask, QueryMTAndPIVo vo, int flag) {
        Date reTime = null;
        /**
         * 1：开始时间。2：结束时间
         * */
        if (flag == 1) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(vo.getValidityStartTime());
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("小时")) {
                calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + vo.getPeriodValue() * subTask.getCycle());//让小时增加周期值
            }
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("日")) {
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue() * subTask.getCycle());//让日增加周期值
            }
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("周")) {
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue() * subTask.getCycle() * 7);//让周增加周期值
            }
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("月")) {
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + vo.getPeriodValue() * subTask.getCycle());//让月增加周期值
            }
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("年")) {
                calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + vo.getPeriodValue() * subTask.getCycle());//让年增加周期值
            }
            reTime = calendar.getTime();
        } else if (flag == 2) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(vo.getValidityStartTime());
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("小时")) {
                calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + vo.getPeriodValue() * subTask.getCycle());//让小时增加周期值
            }
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("日")) {
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue() * subTask.getCycle());//让日增加周期值
            }
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("周")) {
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue() * subTask.getCycle() * 7);//让周增加周期值
            }
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("月")) {
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + vo.getPeriodValue() * subTask.getCycle());//让月增加周期值
            }
            if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("年")) {
                calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + vo.getPeriodValue() * subTask.getCycle());//让年增加周期值
            }
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(calendar.getTime());
            if (null != vo.getCommandId() && vo.getCommandId() != "") {
                calendar1.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + Integer.parseInt(vo.getCommandId()));//让小时增加用户的耗时
            } else {
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("小时")) {
                    calendar1.set(Calendar.HOUR_OF_DAY, calendar1.get(Calendar.HOUR_OF_DAY) + vo.getPeriodValue());//让小时增加周期值
                }
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("日")) {
                    calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue());//让日增加周期值
                }
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("周")) {
                    calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH) + vo.getPeriodValue() * 7);//让周增加周期值
                }
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("月")) {
                    calendar1.set(Calendar.MONTH, calendar1.get(Calendar.MONTH) + vo.getPeriodValue());//让月增加周期值
                }
                if (null != vo.getPeriodUnit() && vo.getPeriodUnit().equals("年")) {
                    calendar1.set(Calendar.YEAR, calendar1.get(Calendar.YEAR) + vo.getPeriodValue());//让年增加周期值
                }
            }
            reTime = calendar1.getTime();
        }
        return reTime;
    }

    /**
     * 封装任务信息
     *
     * @param subTask   子任务信息
     * @param startTime 计划开始时间
     * @param endTime   计划结束时间
     * @param taskName  主任务名称
     * @return PatrolInspection 封装好的任务信息
     */
    private PatrolInspection formatPTaskInfo(QueryMTAndPIVo subTask, Date startTime, Date endTime, String taskName) {
        PatrolInspection patrolInspection = new PatrolInspection();
        patrolInspection.setTaskType(subTask.getTaskType());//set任务类型
        patrolInspection.setTaskName(taskName);//set任务名称
        patrolInspection.setTaskContent(subTask.getTaskContent());//set任务内容
        patrolInspection.setIsPeriodicTask(new Short("0"));//set是否周期任务
        patrolInspection.setWorkInstanceId(subTask.getWorkInstanceId());//set工作内容ID
        patrolInspection.setCommandId(subTask.getCommandId());//set相关工作指令
        patrolInspection.setPlanId(subTask.getPlanId());//set相关工作计划
        patrolInspection.setOrgId(subTask.getOrgId());//set创建组织
        patrolInspection.setCreateTime(new Date());//set创建时间
        patrolInspection.setModifyTime(new Date());//set修改时间
        patrolInspection.setRemark(subTask.getRemark());//set备注
        patrolInspection.setParentId(null == subTask.getValidityStartTime() ? subTask.getParentId() : subTask.getTaskId());//根据周期时间来判定取父id还是主键id
        patrolInspection.setPatrolInspectionId(UniqueUtil.uuid());//set主键ID
        patrolInspection.setCreateUserId(subTask.getCreateUserId());//set创建人
        patrolInspection.setModifyUserId(subTask.getModifyUserId());//set修改人
        patrolInspection.setAuditStatus(new Short("-1")); // -1 正在审核；1 审核通过；0审核不通过
        patrolInspection.setIsDelete(new Short("0")); // 状态0正常；1是删除
        patrolInspection.setIsEnable(new Short("1"));// 状态1是启用；0是关闭
        patrolInspection.setTaskStatus(new Short("2"));// 1 审核处理中；2 执行中；3 已完成
        patrolInspection.setNode(new Short("1")); // 当前节点
        patrolInspection.setPlanStartTime(startTime);//计划开始时间
        patrolInspection.setPlanEndTime(endTime);//计划结束时间
        //set第几次子任务
        patrolInspection.setCycle(null == subTask.getCycle() ? 1 : subTask.getCycle() + 1);
        return patrolInspection;
    }

    /**
     * 根据子任务的计划开始时间选择最后一个子任务的信息
     *
     * @param subTaskList 子任务列表
     * @return QueryMTAndPIVo 子任务信息
     */
    private QueryMTAndPIVo getLastInfo(List<QueryMTAndPIVo> subTaskList) {
        //对list中的元素进行排序
        Collections.sort(subTaskList, (o1, o2) -> o1.getPlanStartTime().compareTo(o2.getPlanStartTime()));
        //对排序好的list取最后一个
        QueryMTAndPIVo returnVo = subTaskList.get(subTaskList.size() - 1);
        return returnVo;
    }
}